package com.help10000.rms.mvp.presenter

import android.util.Log
import com.amir.common.api.CustomObserver
import com.amir.common.beans.BaseResult
import com.amir.common.beans.DefaultCityEntity
import com.amir.common.beans.ZoneEntity
import com.amir.common.mvp.model.Model
import com.amir.common.mvp.presenter.BasePresenter
import com.amir.common.utils.Constant
import com.amir.common.utils.SPUtils
import com.amir.common.utils.Utils
import com.help10000.rms.mvp.view.AddressEditView
import com.help10000.rms.ui.activitys.mine.address.AddAddressActivity
import com.help10000.rms.ui.activitys.mine.address.EditAddressActivity
import com.help10000.rms.utils.LocationManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class EditAddressPresenter(view: AddressEditView) : BasePresenter<AddressEditView>(view) {
    // 自定义协程作用域，绑定生命周期（Job用于取消）
    private val coroutineScope = CoroutineScope(Dispatchers.Main + Job())


    /**
     * 初始化
     */
    fun init() {
        val accessToken = SPUtils.getString(Constant.AccessToken)
        val templateCode = SPUtils.getString(Constant.TemplateCode)
        val appId = SPUtils.getString(Constant.APPId)
        val initDefaultZone = Model.getServer().AddressInit(accessToken, appId, templateCode)
        Model.getObservable(initDefaultZone, object : CustomObserver<DefaultCityEntity>(mvpView) {

            override fun success(t: DefaultCityEntity) {
                mvpView?.initSuccess(t.data?.TempleteInfo)
            }
        })
    }

    /**
     * 添加地址
     */
    fun addAddress(
        tel: String,
        contact: String,
        provinceId: Int,
        cityId: Int,
        townId: Int,
        detailZone: String,
        activity: AddAddressActivity
    ) {
        CoroutineScope(Dispatchers.IO).launch {
            val (lat, lng) = LocationManager.getLocation(activity)
            Log.d("添加地址定位", "获取到经纬度：lat=$lat, lng=$lng")
            val AccessToken = SPUtils.getString(Constant.AccessToken)
            val Latitude = lat
            val Longitude = lng
            val addAddress = Model.getServer().addAddress(
                AccessToken,
                tel,
                contact,
                provinceId,
                cityId,
                townId,
                detailZone,
                Latitude,
                Longitude
            )
            withContext(Dispatchers.Main) {
                Model.getObservable(addAddress, object : CustomObserver<BaseResult>(mvpView) {

                    override fun success(t: BaseResult) {
                        mvpView?.onSuccess()
                    }
                })
            }
        }
    }

    /**
     * 修改地址
     */
    fun editAddress(
        addressId: Int,
        tel: String,
        contact: String,
        provinceId: Int,
        cityId: Int,
        townId: Int,
        detailZone: String,
        activity:AddAddressActivity
    ) {
        CoroutineScope(Dispatchers.IO).launch {
            val (lat, lng) = LocationManager.getLocation(activity)
            Log.d("修改地址定位", "获取到经纬度：lat=$lat, lng=$lng")
            val AccessToken = SPUtils.getString(Constant.AccessToken)
            val Latitude = lat
            val Longitude = lng
            val addAddress = Model.getServer().editAddress(
                AccessToken,
                addressId,
                tel,
                contact,
                provinceId,
                cityId,
                townId,
                detailZone,
                Latitude,
                Longitude
            )
            withContext(Dispatchers.Main) {
                Model.getObservable(addAddress, object : CustomObserver<BaseResult>(mvpView) {

                    override fun success(t: BaseResult) {
                        mvpView?.onSuccess()
                    }
                })
            }
        }
    }

    /**
     * 获取地区信息
     */
    fun getZoneInfo() {
        val AccessToken = SPUtils.getString(Constant.AccessToken)
        val zone = Model.getServer().zoneInfo(AccessToken)
        Model.getObservable(zone, object : CustomObserver<ZoneEntity>(mvpView) {

            override fun success(t: ZoneEntity) {
                mvpView?.onZoneDataSuccess(t)
            }
        })
    }
    // 在Presenter销毁时调用，取消所有协程
    fun onDestroy() {
        coroutineScope.cancel()
    }
}